﻿using CommonDevelop;
using CommonEngine;
using ManageDto;
using ManageService;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using WebAdmin.Handler;

namespace WebAdmin.API
{
    /// <summary>
    /// 文件图片
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class FilePicController : BaseWebApiController
    {
        private readonly IPicService _PicService;
        private readonly IPathProvider pathProvider;
        /// <summary>
        /// 构造注入
        /// </summary>
        public FilePicController(IPicService PicService, IPathProvider pathProvider)
        {
            this._PicService = PicService;
            this.pathProvider = pathProvider;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        [HttpPost]
        [DisableRequestSizeLimit]
        public ActionResult Post(string GroupNo)
        {
            // POST api/FilePic/?GroupNo=dce42a5a-94f1-44b2-a4dc-581f45ab8146
            if (string.IsNullOrEmpty(GroupNo))
            {
                var RM = new { resultCode = 0, resultMsg = "GroupNo为空，上传失败" };
                return new JsonResult(RM);
            }

            //---附件分组NO--要求是Guid的
            string KeyP = GroupNo.ToGuid().HasValue ? GroupNo.ToGuid().Value.ToString("N") : null;
            string root = string.Empty;
            string FileType = null;
            string CurrGroupNo = string.Empty;
            if (!string.IsNullOrEmpty(KeyP))
            {
                FileType = "/Enc/Uploads/API/" + KeyP + "/";
                root = this.pathProvider.WebRootPath + FileType;
                CurrGroupNo = GroupNo;
            }

            if (string.IsNullOrEmpty(FileType) || string.IsNullOrWhiteSpace(CurrGroupNo) || string.IsNullOrEmpty(root))
            {
                var RM = new { resultCode = 0, resultMsg = "参数不足，上传失败" };
                return new JsonResult(RM);
            }

            //如果不存在就创建file文件夹
            if (Directory.Exists(root) == false)
                Directory.CreateDirectory(root);

            string errorMsg = null;
            string V_url = null;
            foreach (var file in Request.Form.Files)
            {
                string uploadName = CommonOP.RNGRandomStr() + file.FileName.TrimStart('\"').TrimEnd('\"');
                string uploadExp = Path.GetExtension(uploadName);
                string fileAddrsss = root + uploadName;
                string url = fileAddrsss.Replace(root, FileType);
                using (FileStream fs = System.IO.File.Create(fileAddrsss))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }

                V_url = url;    //这里规定场景下，一次只接收一个文件，大小不能超过4M
                if (this.MakeFileMsg(CurrGroupNo, root, uploadName, uploadExp, fileAddrsss, url, out errorMsg))
                    break;
            }

            if (string.IsNullOrEmpty(errorMsg))
            {
                var RM = new { code = 200, info = "OK", url = V_url };
                return new JsonResult(RM);
            }
            else
            {
                var RM = new { code = 400, info = errorMsg };
                return new JsonResult(RM);
            }
        }

        //定义允许上传的文件扩展名
        string extStr = "gif,jpg,jpeg,png,bmp";
        /// <summary>
        /// 处理保存文件信息
        /// </summary>
        private bool MakeFileMsg(string GroupNo, string Folder, string uploadName, string uploadExp, string fileAddrsss, string url, out string errorMsg)
        {
            errorMsg = null;
            if (string.IsNullOrEmpty(GroupNo))
            {
                errorMsg = "附件组编号丢失";
                return true;
            }
            if (string.IsNullOrEmpty(uploadExp) || Array.IndexOf(extStr.Split(','), uploadExp.Substring(1).ToLower()) == -1)
            {
                errorMsg = "上传文件不属于图片类型。";
                return true;
            }

            string DomainPath = this.pathProvider.GetHostUri(this.Request);
            PicDto pic = new PicDto();
            pic.PicGroupNo = GroupNo;
            pic.PicFolder = Folder;
            pic.PicName = uploadName;
            pic.PicEx = uploadExp;
            pic.PicUrl = DomainPath + url;
            pic.PicAddress = fileAddrsss;

            this._PicService.SavePic(pic);
            return false;
        }
    }
}